package com.example.springback.service;

import com.example.springback.common.RetireAgeCalculator;
import com.example.springback.domain.Employee;
import com.example.springback.exception.CustomException;
import com.example.springback.mapper.EmployeeMapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import java.time.LocalDate;
import java.time.Period;
import java.time.format.DateTimeFormatter;

import java.util.List;

@Service
public class EmployeeService {
    @Resource
    EmployeeMapper employeeMapper;
    public Employee selectOne(String employeeId,Integer enterpriseId ) {
        return employeeMapper.selectByPrimaryKey(employeeId,enterpriseId );
    }

    public PageInfo<Employee> selectPage(Employee employee,Integer pageNumber, Integer pageSize) {
        PageHelper.startPage(pageNumber,pageSize);
        List<Employee> employees=employeeMapper.selectAll(employee);
        return PageInfo.of(employees);
    }

    public void add(Employee employee) {
        int count =employeeMapper.selectEmployeeNumber(employee.getEnterpriseId());
        String formattedNumber ="1"+ String.format("%05d", count+1); // 格式化为6位，不足补0
        employee.setEmployeeId(formattedNumber);
        employeeMapper.insert(employee);
    }

    public void update(Employee employee) {
        employeeMapper.updateByPrimaryKey(employee);
    }

    public void delete(String employeeId,Integer enterpriseId) {
        employeeMapper.deleteByPrimaryKey(employeeId,enterpriseId);
    }

    public void deleteBatch(List<Employee> employeeList) {
        for (Employee employee:employeeList){
            employeeMapper.deleteByPrimaryKey(employee.getEmployeeId(),employee.getEnterpriseId());
        }
    }


    //计算退休金
    //退休养老金 = 基础养老金 + 个人账户养老金 + 过渡性养老金
    //1、基础养老金= (P + P × i ) ÷ 2 × n × 1%
    // = P × (1 + i）÷ 2 × n × 1%
    //P：退休上年度当地在岗职工月平均工资
    //i：本人历年缴费指数的平均值（缴费指数=本人缴费工资基数÷社会平均工资）
    //n：本人累计缴费年限（含视同缴费）
    //2、个人账户养老金＝ 个人账户储存额 ÷ 计发月数
    //计发月数：根据平均寿命计算，50岁退休按195个月，55岁退休按170个月，
    // 60岁退休按139个月。这个“计发月数”只是用来计算退休当年的养老金，与实际发放月数无关，实际会终身发放。
    public double calculateRetireAccount(double salary,double n,double employeePension,int mouthNumber){
        double retireAccount=0.0;
        double averageSalary=employeeMapper.selectAverageSalary();//获取平均工资P
        double i=salary/averageSalary;//历年缴费指数的平均值,这里简化一下，工资恒定
        if(i>=3) {i=3;}
        if (i<=0.6){i=0.6;}
        double basePension=averageSalary*(1+i)/2*n*0.01;//基础养老金
        double accountPension=employeePension/mouthNumber;//个人账户养老金
        retireAccount=basePension+accountPension;
        return retireAccount;
    }
    public int retire(Employee employee) {
        List<Employee> employees=employeeMapper.selectAll(employee);
        int retireNumber=0;//退休员工人数
        for (Employee e:employees){
            // 生日字符串格式是"YYYY-MM-DD"
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
            LocalDate birthday = LocalDate.parse(e.getEmployeeAge(), formatter);//获取员工出生日期
            String sex=e.getEmployeeSex();//获取员工性别
            LocalDate today = LocalDate.now();//获取当前时间
            LocalDate retireTime;//退休时间
            int originMouth;//计发月数：根据平均寿命计算，50岁退休按195个月，55岁退休按170个月，60岁退休按139个月
            if(sex.equals("男")){
               retireTime= RetireAgeCalculator.manRetireAgeCount(birthday);
               originMouth=139;
            }
            else if (sex.equals("女")){
                retireTime=RetireAgeCalculator.womanRetireAgeCount(birthday);
                originMouth=195;
            }
            else {
                throw new CustomException("500","性别只能为”男“或”女“");
            }
            if(today.isAfter(retireTime)){//退休时间在当前时间之前，就给他退休并计算退休金
                e.setIsleave(1);
                double salary=e.getEmployeeSalary();//工资
                double employeePension=e.getEmployeePension();//个人账户养老金
                Period period=Period.between(birthday,retireTime);//计算退休时的年龄是多少月
                int monthDiff=period.getYears()*12+period.getMonths();
                double n= (monthDiff-20*12)/12;//假设员工从20岁开始没有断缴，计算出累计缴费年限
                int mouthNum=originMouth-RetireAgeCalculator.delayMonths(birthday,sex);//计算延迟退休多少月
                double epension=calculateRetireAccount(salary,n,employeePension,mouthNum);//计算退休金
                e.setEmployeePension(epension);
                retireNumber++;//退休员工人数加一
                employeeMapper.updateByPrimaryKey(e);
            }
        }
        return retireNumber;
    }

    public int countPeople() {
        return employeeMapper.countPeople();
    }
}
